package com.topscore.uke.ui.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageCropActivity;
import com.lzy.imagepicker.ui.ImageGridBottomSheetFragment;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.topscore.uke.R;
import com.topscore.uke.entities.StaffInfoEntity;
import com.topscore.uke.mvp.contractors.LogoutContractor;
import com.topscore.uke.mvp.contractors.UpdateUserInfoContractor;
import com.topscore.uke.mvp.presenters.LogoutPresenter;
import com.topscore.uke.ui.BaseSupportFragment;
import com.topscore.uke.ui.activities.LoginActivity;
import com.topscore.uke.ui.dialog.PictureSingleSelector;
import com.topscore.uke.utils.DisplayImageOptionsManager;
import com.topscore.uke.utils.UserInfoManager;
import com.topscore.utillibrary.util.ImagePickerUtil;
import com.topscore.utillibrary.widget.CircleImageView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class MinePageFragment extends BaseSupportFragment implements LogoutContractor.View, UpdateUserInfoContractor.View {
    @Bind(R.id.tool_bar)
    Toolbar toolBar;
    @Bind(R.id.avatar_iv)
    CircleImageView avatarIv;
    @Bind(R.id.user_login_name_tv)
    TextView userLoginNameTv;
    @Bind(R.id.user_name_edt)
    EditText userNameEdt;
    @Bind(R.id.nick_name_edt)
    EditText nickNameEdt;
    @Bind(R.id.exit_btn)
    Button exitBtn;

    private View rootView;

    private boolean isEditing = false;

    private Menu mMenu;

    private PictureSingleSelector mPictureSingleSelector;

    private ImagePickerUtil mPickerUtil;

    private ImageGridBottomSheetFragment mImageGridBottomSheetFragment;

    private LogoutPresenter mLogoutPresenter;


    public MinePageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_mine_page, container, false);
        ButterKnife.bind(this, rootView);
        mLogoutPresenter = new LogoutPresenter(this);
        initViews();
        return rootView;
    }

    private void initViews() {
        initToolBar();
        mPickerUtil = ImagePickerUtil.getInstance(getActivity());
        mPickerUtil.initAvatarPicker();

        avatarIv.setOnClickListener(v -> {
            if (mPictureSingleSelector == null) {
                mPictureSingleSelector = new PictureSingleSelector(getActivity(),
                        new PictureSingleSelector.PictureSelectedListener() {
                            @Override
                            public void onSelectFromCamera() {
                                ImagePicker.getInstance().takePicture(MinePageFragment.this, ImagePicker.REQUEST_CODE_TAKE);
                            }

                            @Override
                            public void onSelectFromGallery() {
                                if (mImageGridBottomSheetFragment == null) {
                                    mImageGridBottomSheetFragment = ImageGridBottomSheetFragment.getInstance(imageItems -> {
                                        if (imageItems != null && imageItems.size() > 0) {
                                            ImageItem item = imageItems.get(0);
                                            ImageLoader.getInstance().displayImage("file://" + item.path,
                                                    avatarIv,
                                                    DisplayImageOptionsManager.getInstance().getAvatarOptions());
                                        }

                                    });
                                }
                                mImageGridBottomSheetFragment.show(getActivity().getSupportFragmentManager(), "mImageGridBottomSheetFragment");
                            }
                        });
            }
            mPictureSingleSelector.show();
        });
        exitBtn.setOnClickListener(view -> mLogoutPresenter.logout());
        setupEditEnable();
        setupByData();
    }

    private void setupByData() {
        ImageLoader.getInstance().displayImage(UserInfoManager.getUserInfo().getImageUrl(),
                avatarIv,
                DisplayImageOptionsManager.getInstance().getAvatarOptions());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImagePicker.REQUEST_CODE_TAKE && resultCode == getActivity().RESULT_OK) {
            ImagePicker imagePicker = ImagePicker.getInstance();
            ImagePicker.galleryAddPic(mContext, imagePicker.getTakeImageFile());
            ImageItem imageItem = new ImageItem();
            imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
            imagePicker.clearSelectedImages();
            imagePicker.addSelectedImageItem(0, imageItem, true);
            if (imagePicker.isCrop()) {
                Intent intent = new Intent(mContext, ImageCropActivity.class);
                startActivityForResult(intent, ImagePicker.REQUEST_CODE_CROP);  //单选需要裁剪，进入裁剪界面
            }
        }

        if (requestCode == ImagePicker.REQUEST_CODE_CROP && resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            ArrayList<ImageItem> imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            ImageItem item = imageItems.get(0);
            String filePath = item.path;
            ImageLoader.getInstance().displayImage("file://" + filePath,
                    avatarIv, DisplayImageOptionsManager.getInstance().getAvatarOptions());
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_edit, menu);
        mMenu = menu;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_logout:
                mLogoutPresenter.logout();
                break;
            case R.id.action_edit:
                setupEditing();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupEditing() {
        if (isEditing) {
            setupEditEnable();
            mMenu.findItem(R.id.action_edit).setTitle("编辑");
            isEditing = false;
        } else {
            setupEditable();
            mMenu.findItem(R.id.action_edit).setTitle("完成");
            isEditing = true;
        }
    }

    private void setupEditEnable() {
        exitBtn.setVisibility(View.GONE);
        userNameEdt.setFocusable(false);
        userNameEdt.setFocusableInTouchMode(false);
        nickNameEdt.setFocusable(false);
        nickNameEdt.setFocusableInTouchMode(false);
    }

    private void setupEditable() {
        exitBtn.setVisibility(View.VISIBLE);
        userNameEdt.setFocusable(true);
        userNameEdt.setFocusableInTouchMode(true);
        nickNameEdt.setFocusable(true);
        nickNameEdt.setFocusableInTouchMode(true);
    }

    private void initToolBar() {
        setHasOptionsMenu(true);
        toolBar.setTitle("");
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolBar);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLogoutSuccess() {
        Toast.makeText(getContext(), "退出成功，请重新登录", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }

    @Override
    public void onGetDataSuccess(StaffInfoEntity data) {
        userLoginNameTv.setText(data.getEmpNum());
        userNameEdt.setHint(data.getEmpName());
        nickNameEdt.setHint(data.getNickName());

    }

    @Override
    public void onLoading(String loadingMessage) {
        showProgressDialog(loadingMessage);
    }

    @Override
    public void onLoadFinished() {
        dismissProgressDialog();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
    }
}
